package com.qriver.auth.server.controller;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.qriver.auth.server.service.AuthService;
import com.qriver.auth.server.utils.JwtAuthenticationRequest;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("jwt")
public class AuthController {
    @Value("Authorization")
    private String tokenHeader;

    @Autowired
    private AuthService authService;
    
    @RequestMapping(value = "token", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject createAuthenticationToken(
    		JwtAuthenticationRequest authenticationRequest) throws Exception {
        //log.info(authenticationRequest.getUsername()+" require logging...");
        final String token = authService.login(authenticationRequest);
        JSONObject json = new JSONObject();
        json.put("data", token);
        return json;
    }

    @RequestMapping(value = "refresh", method = RequestMethod.GET)
    public JSONObject refreshAndGetAuthenticationToken(
            HttpServletRequest request) throws Exception {
        String token = request.getHeader(tokenHeader);
        String refreshedToken = authService.refresh(token);
        JSONObject json = new JSONObject();
        json.put("data", refreshedToken);
        return json;
    }

    @RequestMapping(value = "verify", method = RequestMethod.GET)
    public JSONObject verify(String token) throws Exception {
        authService.validate(token);
        JSONObject json = new JSONObject();
        return json;
    }
}
